<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检索" prop="search">
        <el-input v-model="queryParams.search" placeholder="请输入检索信息" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料" prop="goodsType">
        <el-select v-model="queryParams.goodsType" placeholder="请选择商品类型">
          <el-option label="物料" value="0"></el-option>
          <el-option label="原料" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="仓库" prop="wareNameList">
        <el-cascader v-model="queryParams.wareNameList" :options="wareList" :props="props" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="生产批号" prop="productNameList">
        <el-cascader v-model="queryParams.productNameList" :options="productList" :props="props1" clearable></el-cascader>
      </el-form-item>

      <el-form-item label="盘点类型" prop="checkType">
        <el-select v-model="queryParams.checkType" placeholder="请选择商品类型">
          <el-option label="物料" value="0"></el-option>
          <el-option label="原料" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择日期" prop="dateTime">
        <el-date-picker clearable v-model="queryParams.dateTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="负责人" prop="createBy">
        <el-select v-model="queryParams.createBy" placeholder="请选择负责人">
          <el-option v-for="item in createByList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['wms:check:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['wms:check:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['wms:check:remove']">删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="50" label="编号" />
      <el-table-column label="单据号" align="center" prop="orderId" width="180" />
      <el-table-column label="物料类型" align="center" prop="goodsType">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.goodsType == '0'">
            物料
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.goodsType == '1'">
            原料
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="wareNameDto" width="100">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.wareNameDto != null">
            {{ scope.row.wareNameDto }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无仓库
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="库区" align="center" prop="wareAreaDto" width="100">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.wareAreaDto != null">
            {{ scope.row.wareAreaDto }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无库区
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="库位" align="center" prop="warePositionDto" width="100">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.warePositionDto != null">
            {{ scope.row.warePositionDto }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无库位
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生产单位" align="center" prop="productName" width="100">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.productName != null">
            {{ scope.row.productName }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无生产单位
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生产批号" align="center" prop="batchName" width="180">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.batchName != null">
            {{ scope.row.batchName }}
          </el-tag>
          <el-tag effect="dark" type="info" v-else>
            暂无生产批号
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="盘点类型" align="center" prop="checkType">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger" v-if="scope.row.checkType == '0'">
            物料
          </el-tag>
          <el-tag effect="dark" type="info" v-else-if="scope.row.checkType == '1'">
            原料
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="库存月份" align="center" prop="wareMon" />
      <el-table-column label="盘点日期" width="180" align="center" prop="createTime">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger">
            {{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="createBy">
        <template slot-scope="scope">
          <el-tag effect="dark" type="danger">
            {{ scope.row.createBy }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="现库存" align="center" prop="wareTotalNum" />
      <el-table-column label="实际库存" align="center" prop="wareNum" />
      <el-table-column label="状态" align="center" prop="checkStatus">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.checkStatus" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:check:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['wms:check:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改盘点信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据">
          <el-select v-if="form.id == null" v-model="form.orderId" placeholder="请输入单据id" ref="cascader"
            @change="handleShowByOrder(form.orderId)">
            <el-option v-for="item in orderIdList" :key="item.id" :label="item.orderId" :value="item.id"></el-option>
          </el-select>
          <el-input v-else v-model="form.orderId" placeholder="请输入单据id" :disabled="true" />
        </el-form-item>

        <el-form-item label="盘点类型" prop="checkType">
          <el-select v-model="form.checkType" placeholder="请选择盘点类型" :disabled="form.id != null">
            <el-option label="物料" value="0"></el-option>
            <el-option label="原料" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="材料类型" prop="goodsType">
          <el-select v-model="form.goodsType" placeholder="请选择材料类型">
            <el-option label="物料" value="0"></el-option>
            <el-option label="原料" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库存月份" prop="wareMon">
          <el-date-picker :disabled="true" clearable v-model="form.wareMon" type="date" value-format="yyyy-MM-dd"
            placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="实际库存" prop="wareNum">
          <el-input-number :disabled="true" v-model="form.wareNum" :min="0" :max="99999"
            label="请输入实际库存"></el-input-number>
        </el-form-item>
        <el-form-item label="盘点日期" prop="createTime">
          <el-date-picker :disabled="true" clearable v-model="form.createTime" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="仓库" prop="wareNameList">
          <el-cascader :disabled="form.id != null" v-model="form.wareNameList" :options="wareList" :props="props"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="生产批号" prop="productNameList">
          <el-cascader :disabled="form.id != null" v-model="form.productNameList" :options="productList" :props="props1"
            clearable></el-cascader>
        </el-form-item>

        <el-form-item label="负责人" prop="createBy">
          <el-input v-model="form.createBy" placeholder="请输入负责人" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number :disabled="form.id != null" v-model="form.sort" @change="handleChange" :min="0" :max="10"
            label="请选择排序"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInfoList, changeCreateStatus, updateEnterStatus, changeGrainStatus, listGrain, getGrain, delGrain, addGrain, updateGrain } from "@/api/wms/grain";
import { createByListInfo, changeCheckStatus, listCheck, getCheck, delCheck, addCheck, updateCheck } from "@/api/wms/check";
import { getProductTreeNode } from "@/api/wms/product"
import { getCascaderWare } from "@/api/wms/ware"
export default {
  name: "Check",
  data () {
    return {
      orderIdList: [],
      // 生产厂家
      productList: [],
      props1: {
        value: 'id',
        label: 'name',
        children: "children"
      },
      //仓库
      wareList: [],
      props: {
        value: 'id',
        label: 'wareName',
        children: "children"
      },
      // 负责人
      createByList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点信息表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        sort: '1',
        wareNum: '1'
      },
      // 表单校验
      rules: {
        createBy: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        wareNameList: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        productNameList: [
          { required: true, message: "生产批号不能为空", trigger: "blur" }
        ],
        checkId: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
        goodsType: [
          { required: true, message: "请选择材料类型", trigger: "blur" }
        ],
        checkType: [
          { required: true, message: "请选择盘点类型", trigger: "blur" }
        ],
        wareMon: [
          { required: true, message: "请选择库存月份", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "请选择盘点日期", trigger: "blur" }
        ],
        wareNum: [
          { required: true, message: "请选择库存数量", trigger: "blur" }
        ],
      }
    };
  },
  created () {
    this.getList();
    this.getCreateByList();
    this.getWareList();
    this.getProductTreeList();
  },
  methods: {
    handleShowByOrder (orderId) {
      getGrain(orderId).then(res => {
        this.form.orderId = res.data.orderId
        this.form.productNameList = res.data.productName
        this.form.wareNameList = res.data.wareName
        this.form.createBy = res.data.createBy
        this.form.wareMon = res.data.createTime
        this.form.createTime = new Date()
        var goodsList = res.data.goodsList
        this.form.wareNum = 0;
        if (goodsList != null) {
          goodsList.forEach(element => {
            if (element.parentId != null && element.parentId != 0)
              this.form.wareNum += element.goodsNum
          });
        }
      })
    },
    // 获取所有单据Id
    getOrder () {
      getInfoList().then(res => {
        this.orderIdList = res.data
      })
    },
    handleChange (value) {
      this.form.sort = value
    },
    // 获取生产单位树形结构
    getProductTreeList () {
      getProductTreeNode().then(res => {
        this.productList = res.data
      })
    },
    // 格式化数据，递归将空的children置为undefined
    formatData (data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.formatData(data[i].children)
        }
      }
      return data;
    },
    // 获取仓库信息
    getWareList () {
      getCascaderWare().then(res => {
        this.wareList = this.formatData(res.data)
      })
    },
    // 获取全部负责人
    getCreateByList () {
      createByListInfo().then(res => {
        this.createByList = res.data
      })
    },
    // 修改盘点状态
    handleStatusChange (row) {
      let text = row.checkStatus === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '"吗？').then(function () {
        return changeCheckStatus(row.id, row.checkStatus);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        this.getList()
      }).catch(function () {
        row.checkStatus = row.checkStatus === "0" ? "1" : "0";
      });
    },
    /** 查询盘点信息列表 */
    getList () {
      this.loading = true;
      listCheck(this.queryParams).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        sort: '1',
        wareNum: '1'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.getOrder()
      this.reset();
      this.open = true;
      this.title = "添加盘点信息";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids
      getCheck(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改盘点信息";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {

          addCheck(this.form).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除盘点信息编号为"' + ids + '"的数据项？').then(function () {
        return delCheck(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('wms/check/export', {
        ...this.queryParams
      }, `check_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
